from rest_framework.serializers import ModelSerializer
from apps.goods.models import SKUImage,SKU
from rest_framework.pagination import PageNumberPagination
from  fdfs_client.client import Fdfs_client
from rest_framework import status

class SKUImageModelSerializer(ModelSerializer):
    """商品图片序列化器"""

    def update(self, instance, validated_data):
        """修改序列化器的更新图片方法"""
        #更新fastdfs服务器图片信息
        cli=Fdfs_client('utils/fastdfs/client.conf') #获得fastdfs服务器连接
        imgdata=cli.upload_by_buffer(validated_data['image'].read()) #fastdfs服务器保存新图片
        if imgdata['Status'] != 'Upload successed.' or len(imgdata['Remote file_id']) < 5: #判断fastdfs服务器是否保存成功
            return Response({'error': 'fastdfs服务器保存失败'},status=status.HTTP_400_BAD_REQUEST)
        instance.image=imgdata['Remote file_id'] #修改mysql
        instance.save()

        return instance


    class Meta:
        model=SKUImage
        fields =('id','sku','image')


class SKUModelSerializer(ModelSerializer):
    """增加图片查询sku_id序列化器"""

    class Meta:
        model=SKU
        fields=('id','name')



from rest_framework.response import Response
from collections import OrderedDict


class SKUImagePageNumberPagination(PageNumberPagination):
    """图片分页类"""
    page_size=5
    page_size_query_param='pagesize'
    max_page_size = 20


    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('lists', data),
            ('page',self.page.number),
            ('pages',self.page.paginator.num_pages),
            ('pagesize',self.page.paginator.per_page)
        ]))


